import 'dart:convert';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/config/config.dart';

import '../entity/receipt_address_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../views/dialog_manager.dart';

///
/// 管理收货地址
///
class MineAddressManager extends StatefulWidget {
  const MineAddressManager({Key? key}) : super(key: key);

  @override
  State<MineAddressManager> createState() => _MineAddressManagerState();
}

class _MineAddressManagerState extends State<MineAddressManager> {
  List<ReceiptAddressData> datas = [];

  @override
  void initState() {
    super.initState();
    getReceipts();
  }

  getReceipts() async {
    dynamic result = await Api.receiptList();
    ReceiptAddressEntity entity = ReceiptAddressEntity.fromJson(result);
    setState(() {
      datas.clear();
      datas.addAll(entity.data);
    });
  }

  deleteReceipt(String id) async {
    dynamic result = await Api.delReceipt({'id': id});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("删除成功");
      getReceipts();
    }
  }


  Widget getListItem(int index) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10.w, horizontal: 25.w),
      decoration: BoxDecoration(
        color: (Config.colorWhite),
        borderRadius: BorderRadius.circular(10.w),
      ),
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 25.w),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '收货人：${datas[index].username}',
                style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
              ),
              Text(
                datas[index].mobile,
                style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
              ),
            ],
          ),
          Padding(
            padding: EdgeInsets.only(top: 20.w),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Container(
              //   margin: EdgeInsets.only(top: 3.w),
              //   child: Icon(
              //     Icons.location_on_outlined,
              //     size: 30.w,
              //     color: Config.colorText1,
              //   ),
              // ),
              // Padding(
              //   padding: EdgeInsets.only(left: 2.w),
              // ),
              Expanded(
                child: Text(
                  "收货地址：${datas[index].provinceName}${datas[index].cityName}${datas[index].areaName}${datas[index].detail}",
                  style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
                ),
              ),
            ],
          ),
          Padding(
            padding: EdgeInsets.only(top: 15.w),
          ),
          Divider(
            color: Config.colorDivider,
            height: 2.w,
            thickness: 2.w,
          ),
          Padding(
            padding: EdgeInsets.only(top: 15.w),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Opacity(
                opacity: datas[index].isDefault == "1" ? 1 : 0,
                child: Row(
                  children: [
                    Icon(
                      Icons.check_circle_outline,
                      color: Config.colorMain,
                      size: 26.w,
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 12.w),
                    ),
                    Text(
                      "默认地址",
                      style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
                    ),
                  ],
                ),
              ),
              Row(
                children: [
                  InkWell(
                    onTap: () {
                      Routes.navigateTo(context, Routes.mineAddressEdit,
                          params: {"receiptId": datas[index].id}).then((value) {
                        if (value != null && value['result'] == 1) {
                          print('地址有更改，刷新一下');
                          getReceipts();
                        }
                      });
                    },
                    child: Row(
                      children: [
                        Icon(
                          Icons.edit_location_outlined,
                          color: Config.colorText1,
                          size: 25.w,
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 7.w),
                        ),
                        Text(
                          "编辑",
                          style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 20.w),
                  ),
                  InkWell(
                    onTap: () {
                      DialogManager.showDefaultDialog(context, "确认删除地址", () {
                        deleteReceipt(datas[index].id);
                      });
                    },
                    child: Row(
                      children: [
                        Icon(
                          Icons.delete_forever,
                          color: Config.colorText1,
                          size: 25.w,
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 7.w),
                        ),
                        Text(
                          "删除",
                          style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
                        ),
                      ],
                    ),
                  ),
                ],
              )
            ],
          ),
        ],
      ),
    );
  }

  Future<bool> _onWillPop() {
    Routes.router.pop(context, {'result': 1});
    return Future.value(false);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: _onWillPop,
        child: Scaffold(
          backgroundColor: Config.colorBg2,
          appBar: AppBar(
            title: const Text('管理收货地址'),
            centerTitle: true,
            leading: IconButton(
                onPressed: () {
                  Routes.router.pop(context, {'result': 1});
                },
                icon: const Icon(Icons.arrow_back)),
          ),
          body: SizedBox(
            width: double.infinity,
            height: double.infinity,
            child: Stack(
              children: [
                Container(
                  width: double.infinity,
                  height: double.infinity,
                  padding: EdgeInsets.only(bottom: 90.w),
                  // decoration: BoxDecoration(
                  //   color: (Config.colorWhite),
                  //   borderRadius: BorderRadius.circular(12.w),
                  // ),
                  child: ListView.builder(
                    shrinkWrap: true,
                    physics: const BouncingScrollPhysics(),
                    itemCount: datas.length,
                    padding: EdgeInsets.symmetric(vertical: 10.w, horizontal: 0.w),
                    itemBuilder: (BuildContext context, int index) {
                      return getListItem(index);
                    },
                  ),
                ),
                Positioned(
                  bottom: 0,
                  child: Container(
                    width: 750.w,
                    height: 100.w,
                    padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 12.w),
                    child: ElevatedButton(
                      clipBehavior: Clip.antiAlias,
                      onPressed: () {
                        Routes.navigateTo(context, Routes.mineAddressEdit).then((value) {
                          if (value != null && value['result'] == 1) {
                            print('地址有更改，刷新一下');
                            getReceipts();
                          }
                        });
                      },
                      style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                      child: const Text('添加新地址'),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}
